package com.flycms.modules.product.service.impl;

import com.flycms.common.pager.Pager;
import com.flycms.common.utils.mark.SnowFlakeUtils;
import com.flycms.common.utils.result.LayResult;
import com.flycms.common.utils.result.Result;
import com.flycms.modules.picture.entity.Picture;
import com.flycms.modules.picture.entity.PictureInfo;
import com.flycms.modules.picture.service.PictureService;
import com.flycms.modules.product.dao.ProductDao;
import com.flycms.modules.product.entity.Product;
import com.flycms.modules.product.service.ProductService;
import com.flycms.modules.site.entity.ContentVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Biz-Boot, All rights reserved
 * 版权：企业之家网 -- 企业建站管理系统<br/>
 * 开发公司：97560.com<br/>
 *
 * @author sun-kaifei
 * @version 1.0 <br/>
 * @email 79678111@qq.com
 * @Date: 17:23 2019/8/14
 */
@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductDao productDao;
    @Autowired
    private PictureService pictureService;
    // ///////////////////////////////
    // /////       增加       ////////
    // ///////////////////////////////

    /**
     * 企业用户发布产品信息
     *
     * @param product
     * @param companyId
     * @param typeId
     * @return
     */
    @Transactional
    public Object addUserProduct(Product product, Long companyId, Integer typeId){
        if(this.checkProductByTitle(product.getSiteId(),product.getTitle(),null)){
            return Result.failure("您已发布过同类名称文章了");
        }
        product.setId(SnowFlakeUtils.nextId());
        product.setContent(pictureService.replaceContent(product.getContent(),companyId,typeId,product.getId()));
        product.setCreateTime(LocalDateTime.now());
        int success=productDao.save(product);
        if(success > 0){
            if(!StringUtils.isEmpty(product.getTitlepic())){
                String fileName=com.flycms.common.utils.StringUtils.getFileName(product.getTitlepic());
                Picture picture=pictureService.findPictureBySignature(companyId,fileName);
                if(!pictureService.checkPictureByInfoId(picture.getId(),product.getId())){
                    PictureInfo info= new PictureInfo();
                    info.setTypeId(typeId);
                    info.setPictureId(picture.getId());
                    info.setInfoId(product.getId());
                    pictureService.savePictureInfo(info);
                }
                int total=pictureService.queryPictureByInfoTotal(companyId,fileName);
                pictureService.updatePictureInfoCount(total,picture.getId());
            }
        }
        return Result.success();
    }
    // ///////////////////////////////
    // /////        刪除      ////////
    // ///////////////////////////////

    /**
     * 按id删除产品信息
     *
     * @param id
     * @return
     */
    public int deleteById(Long id){
        return productDao.deleteById(id);
    }
    // ///////////////////////////////
    // /////        修改      ////////
    // ///////////////////////////////



    // ///////////////////////////////
    // /////        查詢      ////////
    // ///////////////////////////////
    /**
     * 按网站id查询该网站下是否有同标题文章
     *
     * @param siteId
     *         网站id
     * @param title
     *         文章标题
     * @param id
     *         需要排除id
     * @return
     */
    public boolean checkProductByTitle(Long siteId,String title,Long id) {
        int totalCount = productDao.checkProductByTitle(siteId,title,id);
        return totalCount > 0 ? true : false;
    }

    /**
     * 产品翻页列表
     *
     * @param product
     * @param page
     * @param pageSize
     * @param sort
     * @param order
     * @return
     */
    public Object selectProductListPager(Product product, Integer page, Integer pageSize, String sort, String order) {
        StringBuffer whereStr = new StringBuffer(" 1 = 1");
        if (!StringUtils.isEmpty(product.getTitle())) {
            whereStr.append(" and title like concat('%',#{entity.title},'%')");
        }
        if (!StringUtils.isEmpty(product.getColumnId())) {
            whereStr.append(" and column_id = #{entity.columnId}");
        }
        whereStr.append(" and deleted = 0");
        whereStr.append(" and site_id = #{entity.siteId}");
        Pager<Product> pager = new Pager(page, pageSize);
        //排序设置
        if (!StringUtils.isEmpty(sort)) {
            Boolean rank = "desc".equals(order) ? true : false;
            pager.addOrderProperty(sort, rank,true);
        }
        //使用limit进行查询翻页
        pager.addLimitProperty(true);
        //查询条件
        Product entity = new Product();
        entity.setTitle(product.getTitle());
        entity.setSiteId(product.getSiteId());
        entity.setColumnId(product.getColumnId());
        pager.setEntity(entity);
        pager.setWhereStr(whereStr.toString());
        List<Product> sitelsit = productDao.queryList(pager);
        List<ContentVO> volsit = new ArrayList<ContentVO>();
        sitelsit.forEach(bean -> {
            ContentVO vo=new ContentVO();
            vo.setId(bean.getId().toString());
            vo.setTitle(bean.getTitle());
            vo.setModuleType("product");
            vo.setCreateTime(bean.getCreateTime());
            volsit.add(vo);
        });
        return LayResult.success(0, "true", productDao.queryTotal(pager), volsit);
    }
}
